<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_User extends Controller_Template {

    public function action_list() {


        $users = ORM::factory('cheers_sec_user');


        $count = $users->count_all();

        $pagination = Pagination::factory(
                        array(
                            'current_page' => array('source' => 'query_string', 'key' => 'page'),
                            'total_items' => $count,
                            'auto_hide' => 'FALSE',
                        )
        );





        $page_view = $pagination->render();

        $data = ORM::factory('cheers_sec_user')
                ->order_by('chr_uid', 'DESC')
                ->limit($pagination->items_per_page)
                ->offset($pagination->offset)
                ->find_all()
                ->as_array();


        $content = View::factory('admin/administrator/user_list')
                        ->set('data', $data)
                        ->set('count', $count)
                        ->set('page_view', $page_view)->render();


        $this->template = View::factory('admin/template')
                ->set('content', $content);
    }

    public function action_add() {

        if ($_POST) {
            try {
                $user = Arr::get($_POST, 'chr_loginname');


                $_POST['chr_eno'] = $_POST['chr_oid'];
                if (!User::instance()->is_register($user)) {
                    if (User::instance()->register($_POST)) {
                        message::set('添加管理员成功！');
                        Request::current()->redirect('admin/user/add');
                    } else {
                        message::set('管理员添加失败,请检查参数', 'error');
                        $this->request->redirect('/admin/sys/user/add');
                    }
                } else {
                    message::set('该用户已经存在！', 'error');
                    Request::current()->redirect('admin/user/add');
                }

                //重置post
                $_POST = array();
            } catch (ORM_Validation_Exception $e) {
                
            }
        }

        //默认让它显示添加分类的界面吧：
        $content_data['product_ids'] = array();
        $content_data['is_conditional'] = FALSE;
        $catalog_opt_template = array(
            'name_box' => '
            <option value="{id}">{indentation}{name}</option>
            ',
            'indentation' => '&nbsp;|&nbsp;&nbsp;'
        );

        $content_data['catalog_opt'] = self::tree_to_str(self::get_tree($catalog_opt_template));
        $content = view::factory('admin/administrator/user_add', $content_data);
        $this->template = View::factory('admin/template')
                ->set('content', $content);
    }

    public function action_edit() {
        $user_id = $this->request->param('id');

        $user = User::instance($user_id)->get();


        if ($_POST) {
            try {

                $password = Arr::get($_POST, 'chr_password', '');
                if (!empty($password)) {
                    $data['chr_password'] = toolkit::hash($password);
                }
                

                $data['chr_eno'] = Arr::get($_POST, 'chr_oid', '');
                $data['chr_loginname'] = Arr::get($_POST, 'chr_loginname', '');
                $data['chr_passwordhint'] = Arr::get($_POST, 'chr_passwordhint', '');
                $data['chr_username'] = Arr::get($_POST, 'chr_username', '');
                $data['chr_telephone'] = Arr::get($_POST, 'chr_telephone', '');
                $data['chr_enabled'] = Arr::get($_POST, 'chr_enabled', '');

                $user = User::instance()->edit($user_id,$data);

              
                    if ($user) {
                        message::set('编辑管理员成功！');
                        Request::current()->redirect('admin/user/edit/'.$user_id);
                    } else {
                        message::set('编辑管理员失败,请检查参数', 'error');
                        $this->request->redirect('/admin/sys/user/edit/'.$user_id);
                    }
              

                //重置post
                $_POST = array();
            } catch (ORM_Validation_Exception $e) {
                
            }
        }

        //默认让它显示添加分类的界面吧：
        $content_data['product_ids'] = array();
        $content_data['is_conditional'] = FALSE;
        $catalog_opt_template = array(
            'name_box' => '
            <option value="{id}">{indentation}{name}</option>
            ',
            'indentation' => '&nbsp;|&nbsp;&nbsp;'
        );

        $content_data['catalog_opt'] = self::tree_to_str(self::get_tree($catalog_opt_template));
        $content = view::factory('admin/administrator/user_edit', $content_data)
                ->set('data', $user);
        $this->template = View::factory('admin/template')
                ->set('content', $content);
    }

    public function action_delete() {
         $id = $this->request->param('id');
        $user = User::instance()->delete($id);
        if ($user)
            message::set('删除成功！');
        else
            message::set('删除失败!', 'error');
        Request::current()->redirect('/admin/user/list');
    }

    public function action_delete_all() {
        
    }

    public function action_login() {

        if ($_POST) {
            //判断账号和密码是否为空
            if (empty($_POST['username']) || empty($_POST['password'])) {
                message::set('login', '账号和密码不能为空!');
            }
            $data = array();
            $data['username'] = Arr::get($_POST, 'username', '');
            $data['password'] = Arr::get($_POST, 'password', '');

           
            if ($user_id = User::instance()->login($data))
            {
                message::set('登录成功！');
                $session = Session::instance();
                $session->set('chr_uid', $user_id);
               
                Request::current()->redirect('admin/user/list');
            }
            else
            {
                message::set('登录失败请检查账号或者密码！', 'error');
            }
        }


        $this->template = View::factory('admin/login');
    }

    public function action_logout() {
        // Log user out
       Session::instance()->delete('user_id');

        // Redirect to login page
        Request::current()->redirect('admin/user/login');
    }

    /**
     * TODO 方法已更改。需重新写这个注释
     * 此方法可返回（不限深度的）树状结构的“商品分类”数组。
     * @param int $site_id 站点id（因为是静态方法，所以不宜从$this->site_id读取）
     * @param array $template 商品分类的HTML代码模板。参数结构为：
     * 						array(
     * 							'name'=>'包含{name}标签的HTML代码段',			//这是“分类名称”自身的显示模板，例如:'【{name}】'
     * 							'prefix'=>'一段代码',		//是name的前缀，根据树枝的深度循环复制自身，用以达到缩进的树状显示效果，比如：'&nbsp;'
     * 							'whole'=>'包含{name}和{id}标签的HTML代码段'	//每个树枝公用的HTML代码模板，比如:'<option id="{id}">{name}</option>'
     * 						)
     * @param int $parent 父分类id，一般不需要提供此参数，默认为0（即取得0的后代树）
     * @param int $depth 请不要提供此参数，它只通过方法内部递归赋值
     * @return array 当提供了参数$template时，返回已“HTML化”的分类数组。否则，返回标准的“分类id=>分类名称”数组。
     */
    public static function get_tree($template=array(), $parent = 0, $depth = 0) {
        $catalogs = array();
        $children = DB::select(DB::expr('chr_oid,chr_orgname,chr_level'))
                ->from('cheers_sec_organizations')
                ->where('chr_parentid', '=', $parent)
                ->execute();
        if (isset($template['indentation'])) {
            $indentation = str_repeat($template['indentation'], $depth);
        }
        $depth++;

        $children_keys = array();
        foreach ($children as $key => $child) {
            $children_keys[] = $key;
        }

        if (isset($template['last_name_box'])) {
            $children_count = count($children_keys);
            $i = 0;
        }



        foreach ($children_keys as $key => $child_key) {
            $child = $children[$child_key];
            $conditional = $child['chr_level'] == 0 ? FALSE : TRUE;
            if (isset($template['name']) AND $depth > 0) {
                $name_str = $template['name'];
                if ($conditional AND isset($template['conditional_name'])) {
                    $name_str = $template['conditional_name'];
                }
                $replace_name = str_replace('{name}', $child['chr_orgname'], $name_str);
            } else {
                $replace_name = $child['chr_orgname'];
            }

            if (isset($template['last_name_box']) AND $i == $children_count - 1) {
                $last_name_box = $template['last_name_box'];
                if ($conditional AND isset($template['last_conditional_name_box'])) {
                    $last_name_box = $template['last_conditional_name_box'];
                }
                $replace_name = str_replace('{name}', $replace_name, $last_name_box);
                $replace_name = str_replace('{id}', $child['chr_oid'], $replace_name);
            } elseif (isset($template['name_box'])) {
                $name_box = $template['name_box'];

                if ($conditional AND isset($template['conditional_name_box'])) {
                    $name_box = $template['conditional_name_box'];
                }
                $replace_name = str_replace('{name}', $replace_name, $name_box);
                $replace_name = str_replace('{id}', $child['chr_oid'], $replace_name);
            }
            if (isset($template['indentation'])) {
                $replace_name = str_replace('{indentation}', $indentation, $replace_name);
            }
            if (isset($template['last_name_box']))
                $i++;
            $catalogs[$child['chr_oid']]['name'] = $replace_name;
            $catalogs[$child['chr_oid']]['children'] = self::get_tree($template, $child['chr_oid'], $depth);
        }
        return $catalogs;
    }

    /**
     * TODO 方法已更改。需重新写这个注释
     * 此方法将“商品分类”的树状数组各节点的'name'值连接到一起，成为一个字符串
     * @param array $tree “商品分类”的树状数组
     * @param string $str 请不要提供此参数，它只通过方法内部递归赋值
     * @return string  返回所有商品分类集合而成的字符串
     */
    public static function tree_to_str($tree, $template=array(), $str = '', $is_last = true, $depth = 0) {
        $depth++;
        $count = count($tree);
        if (!$is_last AND $count AND $depth > 1 AND isset($template['parent_box_open'])) {
            $str .= $template['parent_box_open'];
        } elseif ($is_last AND $count AND $depth > 1 AND isset($template['parent_box_last_open'])) {
            $str .= $template['parent_box_last_open'];
        }
        $i = 0;
        $is_last = false;
        foreach ($tree as $id => $branch) {
            if ($i == $count - 1) {
                $is_last = true;
            }
            $str = self::tree_to_str($branch['children'], $template, $str . $branch['name'], $is_last, $depth);
            $i++;
        }
        if ($count AND $depth > 1 AND isset($template['parent_box_close'])) {
            $str .= $template['parent_box_close'];
        }
        return $str;
    }

    /**
     * 返回所给分类的所有祖先分类的id
     * @param int $child_id 分类ID
     * @return array 返回$child_id分类的所有祖先分类的id（不包括家族最顶端的'0'），数组内数据排列方向为：长辈->晚辈
     */
    public static function get_parents($child_id) {
        $parents[] = $child_id;
        $parent_id = $child_id;
        while ($parent_id != 0) {
            $catalog_parent = DB::select('chr_parentid')
                    ->from('cheers_sec_organizations')
                    ->where('chr_oid', '=', $parent_id)
                    ->execute();
            $parent_id = $catalog_parent[0]['chr_parentid'];
            if ($parent_id != 0) {
                $parents[] = $parent_id;
            }
        }
        return array_reverse($parents);
    }

    /**
     * 返回所给分了的所有子分类id
     */
    public static function get_childs($parent_id) {

        $childs[] = $parent_id;
        $childs_id = $parent_id;
        while ($childs_id != 0) {
            $catalog_child = DB::select(DB::expr('chr_oid'))
                    ->from('cheers_sec_organizations')
                    ->where('chr_parentid', '=', $childs_id)
                    ->execute();

            $childs_id = $catalog_child[0]['chr_oid'];
            $children_keys = array();
            foreach ($catalog_child as $key => $child) {
                $childs[] = $child['chr_oid'];
            }
        }
        return array_reverse($childs);
    }

    public static function get_left_tree($name_str, $conditional_name_str = null) {
        $catalog_tree_template = array(
            'name_box' => '<li class="catalog_tree_name">' . $name_str . '</li>',
            'last_name_box' => '<li class="catalog_tree_name catalog_tree_last_name">' . $name_str . '</li>',
            'no_conditional' => TRUE
        );
        if ($conditional_name_str !== null) {
            $catalog_tree_template['no_conditional'] = FALSE;
            $catalog_tree_template['conditional_name_box'] = '<li class="catalog_tree_name catelog_tree_conditional_name">' . $conditional_name_str . '</li>';
            $catalog_tree_template['last_conditional_name_box'] = '<li class="catalog_tree_name catalog_tree_last_name catelog_tree_conditional_name">' . $conditional_name_str . '</li>';
        }
        $catalog_str_template = array(
            'parent_box_open' => '<li class="catalog_tree_children"><ol>',
            'parent_box_last_open' => '<li class="catalog_tree_children catalog_tree_last_children"><ol>',
            'parent_box_close' => '</ol></li>'
        );
        return '<ul id="catalog_tree">' . self::tree_to_str(self::get_tree($catalog_tree_template), $catalog_str_template) . '</ul>';
    }

}